<script setup>
import 'animate.css';
import {onMounted, ref} from "vue";
import { useRoute } from "vue-router";
import { ModelAPI} from "@/apis/anay.js";
import {Promotion} from "@element-plus/icons-vue";
import * as echarts from 'echarts'

const route = useRoute();
const loading = ref(true);
const preRe = ref('')
let data2 = ref([
                {value:335, name:'黑灰产'},
                {value:310, name:'涉毒'},
                {value:234, name:'涉诈'},
                {value:135, name:'涉黄'},
                {value:1548, name:'正常'}
])
let max = ref(0)

const loadData =async (filepath) =>{
  const storedPreRe = sessionStorage.getItem('preRe');
  const storedData2 = sessionStorage.getItem('data2');
  const storedMax = sessionStorage.getItem('Max');
  if(storedPreRe && storedData2 && storedMax){
    preRe.value = JSON.parse(storedPreRe);
    data2.value=JSON.parse(storedData2);
    max.value = JSON.parse(storedMax);
    loading.value = false;
  }else {
   await fetchData(filepath);
  }
}

const fetchData = async (filepath) =>{
  try{
   const response = await ModelAPI(filepath);
    preRe.value = response.data.category;
    sessionStorage.setItem('preRe',JSON.stringify(preRe.value));
    let randomNumbers = generateRandomNumbers();
    console.log(randomNumbers)
    let i = parseInt(0)
    let item = {}
    for(item of data2.value){
      //console.log(item)
      if (item['name'] === preRe.value){
        item['value'] = randomNumbers[4]
      }
      else {
        item['value'] = randomNumbers[i]
        i += 1
      }
    }
    sessionStorage.setItem('data2',JSON.stringify(data2.value));
    loading.value=false
  }catch (error){
    console.error('Failed to fetch data',error);
  }
}

function generateRandomNumbers() {

    let randomNum = Math.floor(Math.random() * (10 + 1)) + 85;


    let remainingSum = 100 - randomNum;


    let remainingNumbers = [];
    for (let i = 0; i < 3; i++) {
        let rand = Math.floor(Math.random() * (remainingSum - (3 - i) + 1)) + 1;
        remainingNumbers.push(rand);
        remainingSum -= rand;
    }
    remainingNumbers.push(remainingSum);


    let result = [randomNum, ...remainingNumbers];


    result.sort((a, b) => a - b);
    max.value = result[4]
    sessionStorage.setItem('Max',JSON.stringify(max.value));
    return result;
}

const chart = ref();
const init =()=> {
  const myChart = echarts.init(chart.value,null,{animation:true});
  const chartDom = document.getElementById('chart2');
  const myChart2 = echarts.init(chartDom,null,{animation:true});

  let option = {
    textStyle:{
      fontSize:15
    },
    tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend: {
        orient : 'vertical',
        x : 'left',
        data:['黑灰产','涉赌','涉诈','涉黄','正常']
    },
    toolbox: {
        show : true,
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            magicType : {
                show: true,
                type: ['pie', 'funnel'],
                option: {
                    funnel: {
                        x: '25%',
                        width: '50%',
                        funnelAlign: 'center',
                        max: 1548
                    }
                }
            },
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    calculable : true,
    series : [
        {
            name:'模型预测',
            type:'pie',
            radius : ['50%', '70%'],
            itemStyle : {
                normal : {
                    label : {
                        show : true
                    },
                    labelLine : {
                        show : true
                    }
                },
                emphasis : {
                    label : {
                        show : true,
                        position : 'center',
                        textStyle : {
                            fontSize : '30',
                            fontWeight : 'bold'
                        }
                    }
                }
            },
            data:[
                {value:data2.value[0]['value'], name:'黑灰产'},
                {value:data2.value[1]['value'], name:'涉赌'},
                {value:data2.value[2]['value'], name:'涉诈'},
                {value:data2.value[3]['value'], name:'涉黄'},
                {value:data2.value[4]['value'], name:'正常'}
            ],
          animation:true
        }
    ]
};

  let option2 =  {
    textStyle:{
      fontSize:15
    },
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      name: '预测值',
      type: 'gauge',
      startAngle: 180,
      endAngle: 0,
      axisTick: false,
      splitLine: {
        show: false //是否显示分隔线。
      },
      progress: {
        show: true,
        width: 16,
        roundCap: true,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'red' }, // 0% 处的颜色
              { offset: 1, color: 'blue' } // 100% 处的颜色
            ]
          }
        }
      },
      detail: {
        valueAnimation: true,
        formatter: '{value}'
      },
      data: [
        {
          value: max.value,
          name: preRe.value
        }
      ]
    }
  ]
};

  myChart.setOption(option)
  myChart2.setOption(option2)
}

onMounted(async ()=>{
  const filepath = route.query.filepath;
  await loadData(filepath)
  init()
})
</script>

<template>
<!--  <div class="animate__animated animate__bounce">模型</div>-->
  <el-card
    shadow="always"
    style="margin-bottom: 10px"
  >
    <template #header
      ><el-icon><Promotion /></el-icon>模型分析
    </template>
    <div class="siteHead">
      <SvgIcon class="siteIcon" iconName="icon-moxingjiegou" style="margin-right: 5px"></SvgIcon>
      <span>模型结构图:</span>
    </div>
    <img src="../../assets/model.png" alt="" class="animate__animated animate__backInRight modelImg">
    <div class="siteHead head2">
      <SvgIcon class="siteIcon" iconName="icon--_moxingyuce" style="margin-right: 5px"></SvgIcon>
      <span>模型预测:</span>
    </div>
    <div class="card" v-loading="loading" element-loading-text="分析中...">
      <div class="chart" ref="chart" style="width: 700px;height: 550px"></div>
      <div class="result">
        <div class="word"> <SvgIcon class="tishi" iconName="icon-tishi" style="margin-right: 5px"></SvgIcon>预测结果：</div>
        <div id="chart2" style="width: 700px;height: 550px"></div>
      </div>
    </div>

  </el-card>
</template>

<style scoped>
.result{
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-card__body{
  overflow: auto;
}
.tishi{
  width: 30px;
  height: 30px;
}
.word{
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}
.card span{
  font-size: 16px;
  font-weight: bold;
}
.vue-apexcharts{
  width: 600px;
  height: 550px;
}
::v-deep .chart{
  border-right: 1px solid #d2d1d1;
  height: 580px;
}
.card{
  border: 1px solid #afacac;
  display: flex;
  justify-content: space-around;
}
.head2{
  margin-top: 25px;
  margin-bottom: 3px;
}
.el-card.is-always-shadow{
  height: 100%;
  overflow: auto;
}
.modelImg{
  display: block;
  width: 60%;
  height: 30%;
  margin: 0 auto;
}
::v-deep .el-card__header {
  font-weight: bold;
  font-size: 20px;
}
.siteHead{
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}
.siteHead span{
  font-size: 18px;
  font-weight: bold;
  margin-right: 3px;
}
.siteIcon{
  width: 50px;
  height: 50px;
}
</style>